<?php
class cartSession extends spModel
{
    private $data=null; 
    private $session_id=null; 
    private $minutes_to_expire=86400; // TIME TO MAINTAIN DATA ON DB 
    
    public function __construct(){
      global $SESSION; 
      
      //检查当前终端是否有ID，没有就新建一个ID
      if (isset($_COOKIE['CARTSESSION_ID'])){
        $this->session_id = $_COOKIE['CARTSESSION_ID'];
      }
        $condition = array('session_id' => $this->session_id);
        $query = spClass('SessionModel')->find($condition);
        if (!$query)
        {
            $this->session_id = md5(microtime() . rand(1, 9999999999999999999999999)); // GENERATE A RANDOM ID
            setcookie('CARTSESSION_ID', $this->session_id,time()+$this->minutes_to_expire,WEBDIR);
            $data = array('session_id' => $this->session_id,'updated_on'=>time());
            spClass('SessionModel')->create($data);
        }

      //调用清除过期记录函数
      //$this->expire();
    }
    
    //清除过期记录
    private function expire(){
       $date_to_delete = time()-$this->minutes_to_expire;
       $conditions = 'updated_on<='.$date_to_delete;
       spClass('SessionModel')->delete($conditions); // 删除记录 
    } 
    //清除过期记录
    public function del()
    {
        //echo  $this->session_id;
        $conditions = array('session_id' => $this->session_id);
        spClass('SessionModel')->delete($conditions); // 删除记录
    } 
    //写入修改记录
    public function write($session_data,$session_time=1440){
            
            $data2=array('value'=>$session_data, 'updated_on' => time());
            //dump($data2);
            $condition = array('session_id' => $this->session_id);
            spClass('SessionModel')->update($condition, $data2);
            setcookie('CARTSESSION_ID', $this->session_id,time()+$session_time,WEBDIR);
    
    } 

    public function read()
    {
        // your code
      $condition = array('session_id'=>$this->session_id);
      $query = spClass('SessionModel')->find($condition);
      //dump($query);

        if ($query)
            return $query['value'];
        return '';

    }

  
/* 
TABLE STRUCTURE 
  CREATE TABLE IF NOT EXISTS `tb_session_db` ( 
    `session_id` varchar(32) NOT NULL, 
    `value` blob, 
    `updated_on` datetime DEFAULT NULL, 
    PRIMARY KEY (`session_id`) 
  ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 
*/ 
 
}
?>